import '../plugins/upload';
import '../plugins/jquery.scrltab';
import BootstrapDialog from 'bootstrap3-dialog';
import '../../style/ad-add.less';

import uploadHtml from '../../assets/partials/file/file-upload.html';
import fileEditHtml from '../../assets/partials/file/file-edit.html';

$.addAd = function dialog(groupId) {

    if (groupId == undefined) {
        groupId = $('#tree-panel').find(".selected").attr("data-id");
    }

    if (groupId == undefined) {
        alert("请在左边分组栏选择一个分组");
        return;
    }

    let uploaders = [];

    $(document).on("click", ".ad-add", function(e) {
        e.stopPropagation();
        e.preventDefault();
        $(this).parent().parent().append(
            $("<li>").append(
                $("<input type='file' style='display: inline-block; width: 50%;'>")
            ).append(
                $("<i class='icon icon-add ad-add'>")
            )
        );
        $(this).removeClass("ad-add").addClass("ad-del").addClass("icon-del");
    });

    $(document).on("click", ".ad-del", function(e) {
        e.stopPropagation();
        e.preventDefault();
        let id = $(this).attr("data-id");
        if (id != undefined) {
            $.myAjax({
                url: "ad/delAdFile.do",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({
                    fileId: id
                }),
                success: function(result) {}
            });
        }
        $(this).parent().remove();
    });

    let adDialog = $.dialog({
        title: "编辑广告",
        size: BootstrapDialog.SIZE_WIDE,
        message: $("<div>").html(fileEditHtml),
        onshow: function(dialog) {
            let body = dialog.getModalBody()[0];
            let $moduleTbody = $(body).find('tbody');
            $.myAjax({
                url: "ad/getAdTypeList.do",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({
                    groupId: groupId
                }),
                success: function(result) {
                    let data = result.data;
                    $.each(data, function(index, item) {

                        if (item.isUploadDir == "TRUE") {
                            let $zip = $(body).find('#zip').scrltab();
                            $.each(item.fileDirEntities, function(i, o) {
                                let active = i == 0 ? true : false;
                                $zip.scrltab('addTab', {
                                    title: o.name,
                                    name: o.name,
                                    body: uploadHtml,
                                    active: active,
                                    files: o.dirFileEntities
                                });
                                let uploader = $.initWebUploader({
                                    ele: $zip.find('#' + o.name + '_content'),
                                    url: '/api/ad/upload.do',
                                    formData: {
                                        groupId: groupId,
                                        moduleId: item.id,
                                        dirId: o.id
                                    }
                                });
                                uploaders.push(uploader);
                            });
                        } else {
                            let $tr = $(`<tr>
                              <td>` + item.module + `</td>
                              <td><span>` + item.fileName + `</span><i class="icon icon-add"></i></td>
                              <td>` + item.version + `</td>
                              <td><input type="text" value="` + item.updateInfo + `" style="width: 100%"></td>
                          </tr>`)
                            $moduleTbody.append($tr);

                        }
                        // let $tabmain = $("<div class='tabmain'>").scrltab();
                        // if (item.adDirEntities != undefined && item.adDirEntities.length != 0) {
                        //
                        // } else {
                        //     $tabmain.find(".tabGroup").hide();
                        //     $tabmain.find(".tabBody").css("width", "100%");
                        //
                        //     let active = index == 0 ? true : false;
                        //     $tabmain.scrltab('addTab', {
                        //         title: item.title,
                        //         name: item.title,
                        //         body: uploadHtml,
                        //         active: active,
                        //         files: item.adFileEntities
                        //     });
                        //     let uploader = $.initWebUploader({
                        //         ele: $tabmain.find('#' + item.title + '_content'),
                        //         url: '/api/ad/upload.do',
                        //         formData: {
                        //             groupId: groupId,
                        //             adTypeId: item.id
                        //         }
                        //     });
                        //     uploaders.push(uploader);
                        // }


                        // let active = index == 0 ? true : false;
                        // $tab.scrltab('addTab', {
                        //     title: item.name,
                        //     name: item.type,
                        //     body: upload,
                        //     active: active,
                        //     files: item.adFileEntities
                        // });

                    });
                }
            });
        },
        submit: function(dialog) {
            let totalFile = 0;
            let cancelFile = 0;
            $.each(uploaders, function(index, item) {
                cancelFile += item.getStats().cancelNum;
                let fileLength = item.getFiles().length;
                if (fileLength != 0) {
                    totalFile += item.getFiles().length;
                    item.upload();
                }
            });
            totalFile = totalFile - cancelFile;
            $.dialogShow({
                title: "正在上传文件，请稍候……",
                message: $(`<div class="progress" id="fileProgress">
                              <div class="progress-bar" role="progressbar" aria-valuenow="60"
                                aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
                              </div></div>`),
                onshown: function(progressDialog) {

                    let body = progressDialog.getModalBody()[0];

                    var $progressBar = $(body).find('.progress-bar');

                    let interval = setInterval(function() {

                        let complete = 0;

                        $.each(uploaders, function(index, item) {
                            complete += item.getFiles("complete").length;
                        });
                        console.log((complete / totalFile) * 100 + "%")

                        $progressBar.width((complete / totalFile) * 100 + "%");

                        if (complete == totalFile) {
                            clearInterval(interval);
                            progressDialog.close();
                        }

                    }, 100);
                }
            });

        }
    });

}
